package com.axx.android.profile.tool;

import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.axx.android.LetterApp;
import com.axx.android.R;
import com.axx.android.base.BaseActivity;
import com.axx.android.common.BaseModel;
import com.axx.android.common.Constants;
import com.axx.android.letter.activity.LetterToolActivity;
import com.axx.android.letter.adapter.SectionedSpanSizeLookup;
import com.axx.android.letter.adapter.ToolAdapter;
import com.axx.android.letter.model.CreateOrderResult;
import com.axx.android.letter.model.PayEvent;
import com.axx.android.letter.model.Tool;
import com.axx.android.utils.GsonUtils;
import com.axx.android.utils.HttpUtils;
import com.google.gson.reflect.TypeToken;
import com.tencent.mm.opensdk.modelbase.BaseResp;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.beecloud.BCPay;
import cn.beecloud.BeeCloud;
import cn.beecloud.async.BCCallback;
import cn.beecloud.async.BCResult;
import cn.beecloud.entity.BCPayResult;

public class ToolActivity extends BaseActivity {

    @Bind(R.id.btn_back)
    Button btnBack;
    @Bind(R.id.lv_letter)
    RecyclerView rvTool;
    private int payStyle;
    private int toolId;
    private int buyNum;
    private long money;
    private long unitPrice;
    private CreateOrderResult.PorderBean porder;
    private ToolBuyFragment toolBuyFragment;
    private String toolName;

    @Override
    public int getLayoutId() {
        return R.layout.activity_tool;
    }

    @Override
    public void init(Bundle savedInstanceState) {
        fetchTool();
        initPaySdk();
        EventBus.getDefault().register(this);
    }


    private void fetchTool() {
        Map<String, String> datas = new HashMap<>();
        datas.put("userId", LetterApp.authUser.getId());
        HttpUtils.post(Constants.Url.Profile.PROFILE_TOOLS, datas, new HttpUtils.SJCallBack() {
            @Override
            public void onSuccess(String result) {
                try {
                    BaseModel<Tool> toolBaseModel = GsonUtils.fromJson(result, new TypeToken<BaseModel<Tool>>() {
                    });
                    if (toolBaseModel.isSuccess()) {
                        handleToolResult(toolBaseModel.data);
                    } else {
                        showToast(toolBaseModel.message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    showErrorParse();
                }
            }

            @Override
            public void onError() {
                showErrorNet();
            }
        });
    }


    private void handleToolResult(Tool data) {
        initAdapter(data.getToollist());
    }

    private void initAdapter(List<Tool.ToollistBean> title) {
        ToolAdapter toolAdapter = new ToolAdapter(title, this);
        rvTool.setAdapter(toolAdapter);
        GridLayoutManager layoutManager = new GridLayoutManager(this, 3);
        SectionedSpanSizeLookup lookup = new SectionedSpanSizeLookup(toolAdapter, layoutManager);
        layoutManager.setSpanSizeLookup(lookup);
        rvTool.setLayoutManager(layoutManager);
        toolAdapter.setItemClick(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Tool.ToollistBean.ToolsBean toolsBean = (Tool.ToollistBean.ToolsBean) view.getTag();
                if (toolsBean.getIsbuy() == 0){
                    showToast("该道具不可购买");
                    return;
                }
                toolBuyFragment = ToolBuyFragment.newInstance(toolsBean, false);
                toolBuyFragment.show(getSupportFragmentManager(), "tag");

                toolId = toolsBean.getId();
                toolName=toolsBean.getName();
                unitPrice = (long) (toolsBean.getPrice() * 100);
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onPayEvent(PayEvent payEvent) {
        this.payStyle = payEvent.payStyle;
        this.buyNum = payEvent.buyNum;
        this.money = (long) (payEvent.money * 100);
        showLoading("");
        handleCreateOrder();
    }

    private void handleCreateOrder() {
        HashMap<String, String> map = new HashMap<>();
        map.put("userId", LetterApp.authUser.getId());
        map.put("channelType", payStyle + "");
        map.put("transactionFee", money + "");
        map.put("toolsId", toolId + "");
        map.put("number", buyNum + "");
        map.put("price", unitPrice + "");
        map.put("token", LetterApp.authUser.getToken());
        map.put("type", "1");

        HttpUtils.post(Constants.Url.Pay.PAY_CREATE_ORDER, map, new HttpUtils.SJCallBack() {
            @Override
            public void onSuccess(String result) {
                try {
                    BaseModel<CreateOrderResult> createOrderResultBaseModel = GsonUtils.fromJson(result, new TypeToken<BaseModel<CreateOrderResult>>() {
                    });
                    if (createOrderResultBaseModel.isSuccess()) {
                        pay(createOrderResultBaseModel.data.getPorder());
                    } else {
                        hideLoading();
                        showToast("支付失败");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    hideLoading();
                    showToast("支付失败");
                }
            }

            @Override
            public void onError() {
                hideLoading();
                showToast("支付失败");
            }
        });
    }

    private void pay(CreateOrderResult.PorderBean porder) {
        this.porder = porder;
        if (payStyle == 1) {
            wxPay(porder);
        } else {
            aliPay(porder);
        }
    }

    private void aliPay(CreateOrderResult.PorderBean porder) {
        BCPay.getInstance(ToolActivity.this).reqAliPaymentAsync(
                "爱写信订单-" +toolName,
                porder.getTransactionFee(),
                porder.getId(),
                null,
                bcCallback);
    }

    BCCallback bcCallback = new BCCallback() {
        @Override
        public void done(BCResult result) {
            final BCPayResult bcPayResult = (BCPayResult) result;
            if (bcPayResult.getResult().equals(BCPayResult.RESULT_SUCCESS)) {
                //购买成功
                handlePost();
            } else {
                hideLoading();
                showToast(bcPayResult.getErrMsg());
            }
        }
    };

    private void handlePost() {
        HashMap<String, String> stringHashMap = new HashMap<>();
        stringHashMap.put("number", buyNum + "");
        stringHashMap.put("userId", LetterApp.authUser.getId());
        stringHashMap.put("toolsId", toolId + "");
        stringHashMap.put("transactionId", porder.getId());
        stringHashMap.put("token", LetterApp.authUser.getToken());
        HttpUtils.post(Constants.Url.Bag.BAG_BUY, stringHashMap, new HttpUtils.SJCallBack() {
            @Override
            public void onSuccess(String result) {
                hideLoading();
                try {
                    BaseModel baseModel = GsonUtils.fromJson(result, new TypeToken<BaseModel>() {
                    });
                    if (baseModel.isSuccess()) {
                        showToast(baseModel.message);
                        fetchTool();
                    } else {
                        showToast(baseModel.message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    showErrorParse();
                }
            }

            @Override
            public void onError() {
                hideLoading();
                showErrorNet();
            }
        });


    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onWxPayEvent(BaseResp event) {
        if (event.errCode == 0) {
            //购买成功
            handlePost();

        } else {
            hideLoading();
            showToast("支付失败");
        }
    }

    private void wxPay(CreateOrderResult.PorderBean porder) {
        if (BCPay.isWXAppInstalledAndSupported() &&
                BCPay.isWXPaySupported()) {

            BCPay.getInstance(ToolActivity.this).reqWXPaymentAsync(
                    "爱写信订单-" +toolName,
                    porder.getTransactionFee(),
                    porder.getId(),
                    null,
                    bcCallback);

        } else {
            showToast("您尚未安装微信或者安装的微信版本不支持");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private void initPaySdk() {
        BeeCloud.setSandbox(false);
        BeeCloud.setAppIdAndSecret(Constants.APP_ID,
                Constants.APP_SECRET);

        String initInfo = BCPay.initWechatPay(ToolActivity.this, Constants.WX_APP_ID);
        if (initInfo != null) {
            Toast.makeText(this, "微信初始化失败：" + initInfo, Toast.LENGTH_LONG).show();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
